package com.hzgj.bcl.soa.command;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hzgj.bcl.soa.collector.Collectors;
import com.hzgj.bcl.soa.collector.JmxCollector;
import com.hzgj.bcl.soa.config.ReferenceDef;
import com.hzgj.bcl.soa.util.Constants;
import com.hzgj.bcl.soa.util.Pair;

import java.rmi.ConnectException;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/18.
 */
public class UpdateClientConfigCommand extends JmxInvokeCommand {

    @Override
    public String getName() {
        return "updateClientConfig";
    }

    @Override
    Map<String, Object> jmxInvoke(JmxCollector jmxCollector, CommandOptions commandOptions, String host, String port) throws ConnectException {
        Map<String, Object> result = Maps.newHashMap();
        try {
            String services = commandOptions.params.get("services")[0];
            String[] version_param = commandOptions.params.get("version");
            String[] group_param = commandOptions.params.get("group");
            String version = null;
            if (version_param != null) {
                version = version_param[0];
            }
            String group = null;
            if (group_param != null) {
                group = group_param[0];
            }
            String[] _ss = services.split(",");
            List<ReferenceDef> referenceDefs = Lists.newArrayList();
            for (String sName : _ss) {
                ReferenceDef referenceDef = new ReferenceDef();
                referenceDef.setGroup(group);
                referenceDef.setVersion(version);
                referenceDef.setService(sName);
                referenceDefs.add(referenceDef);
            }
            Pair<Boolean, String> ret = (Pair<Boolean, String>) jmxCollector.invoke(Constants.getCicadaRouterObjectName(), "updateReference",
                    new Object[]{referenceDefs}, new String[]{List.class.getName()});
            if (ret.getLeft()) {
                result.put("status", "success");
                result.put("message", "update success.");
            } else {
                result.put("message", "Router:" + ret.getRight());
                result.put("status", "failure");
            }
        } catch (Exception e) {
            if (e instanceof ConnectException) {
                Collectors.removeCollector(host, Integer.parseInt(port));
            }
            logger.error("{}", e);
            result.put("message", e.getMessage());
            result.put("status", "failure");
        }
        return result;
    }
}
